package com.example.emos.api.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.example.emos.api.common.util.PageUtils;
import com.example.emos.api.common.util.R;
import com.example.emos.api.controller.form.*;
import com.example.emos.api.db.pojo.TbBusiness;
import com.example.emos.api.db.pojo.TbPackManger;
import com.example.emos.api.service.ModelService;
import com.example.emos.api.service.PackMangerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/packManger")
@Tag(name = "PackMangerController",description = "固件包管理")
public class PackMangerController {
    @Autowired
    private PackMangerService packMangerService;

    @PostMapping("/searchModelByPage")
    @Operation(summary = "型号分页查询")
    public R searchPackMangerByPage(@Valid @RequestBody SearchPackMangerByPageForm form){
        if((form.getStartDate()!=null&&form.getEndDate()==null)||(form.getStartDate()==null&&form.getEndDate()!=null)){
            return R.error("startDate和endDate只能同时为空，或者不为空");
        }
        int page= form.getPage();
        int length= form.getLength();
        int start=(page-1)*length;
        HashMap param= JSONUtil.parse(form).toBean(HashMap.class);
        param.put("start",start);
//        param.put("currentUserId", StpUtil.getLoginIdAsInt());
//        if(!(StpUtil.hasPermission("AMECT:SELECT")||StpUtil.hasPermission("ROOT"))){
//            param.put("userId", StpUtil.getLoginIdAsInt());
//        }
        PageUtils pageUtils=packMangerService.searchPackByPage(param);
        return R.ok().put("page",pageUtils);


    }
    @PostMapping("/insert")
//    @SaCheckPermission(value = {"ROOT", "USER:INSERT"}, mode = SaMode.OR)
    @Operation(summary = "添加设备")
    public R insert(@Valid @RequestBody InsertPackMangerForm form){
        TbPackManger tbPackManger= JSONUtil.parse(form).toBean(TbPackManger.class);
//        tbPackManger.setStatus((byte)1);
//        user.setRole(JSONUtil.parseArray(form.getRole()).toString());
        tbPackManger.setPackList(JSONUtil.parseArray(form.getPackList()).toString());
        tbPackManger.setUrlList(JSONUtil.parseArray(form.getUrlList()).toString());
        tbPackManger.setVerList(JSONUtil.parseArray(form.getVerList()).toString());
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String pTime=  dateFormat.format(new Date());
        String[] pTimes=new String[form.getPackList().length];
        for (int i = 0; i < pTimes.length; i++) {
            pTimes[i]=pTime;
        }
        tbPackManger.setPackTime(JSONUtil.parse(pTimes).toString());
        tbPackManger.setCreateTime(new Date());

        int rows=packMangerService.insertPack(tbPackManger);
        if(rows>0){

            return R.ok().put("rows",rows);
        }else{
            return R.error("设备名称不可重复");
        }
    }
    @PostMapping("/addPack")
    @Operation(summary = "新增固件包")
    public R addPack(@Valid @RequestBody UpdatePackMangerForm form){
        HashMap tbPackManger = packMangerService.selectByPrimaryKey(form.getId());
        try {
            JSONArray packList = JSONUtil.parseArray(tbPackManger.get("packList"));
            JSONArray urlList = JSONUtil.parseArray(tbPackManger.get("urlList"));
            JSONArray verList = JSONUtil.parseArray(tbPackManger.get("verList"));
            JSONArray packTime = JSONUtil.parseArray(tbPackManger.get("packTime"));
//            List<HashMap<String,String>> list=new ArrayList<HashMap<String,String>>();
            @NonNull  String[] packList1 = form.getPackList();
            @NonNull String[] verList1 = form.getVerList();
            @NonNull String[] urlList1 = form.getUrlList();


            if(packList1.length>0 &&urlList1.length>0&&verList1.length>0){
                if(packList1.length==urlList1.length&&urlList1.length==verList1.length){
                    packList.addAll(Arrays.asList(packList1));
                    urlList.addAll(Arrays.asList(urlList1));
                    verList.addAll(Arrays.asList(verList1));
                    SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm");
                  String pTime=  dateFormat.format(new Date());

                    for (int i = 0; i < packList1.length; i++) {
                        packTime.add(pTime);
                    }
//                    for (int i = 0; i < packList.size(); i++) {
//                        HashMap<String, String> p = new HashMap<>();
//                        p.put("name",packList.get(i).toString());
//                        p.put("url",urlList.get(i).toString());
//                        p.put("ver",verList.get(i).toString());
//                        list.add(p);
//                    }
//                    tbPackManger.put("packageCount",list.size());
//                    tbPackManger.put("pName",packList.get(0).toString());
//                    tbPackManger.put("pVersion",verList.get(0).toString());
//                    tbPackManger.put("packs",list);
                    tbPackManger.put("packList",packList.toString());
                    tbPackManger.put("urlList",urlList.toString());
                    tbPackManger.put("verList",verList.toString());
                    tbPackManger.put("packTime",packTime.toString());
                    tbPackManger.put("packageCount",packList.size());
                    tbPackManger.put("pName",packList.get(packList.size()-1).toString());
                    tbPackManger.put("pVersion",verList.get(verList.size()-1).toString());
                    tbPackManger.put("createTime",new Date());
                    int row = packMangerService.update(tbPackManger);
                    return R.ok().put("data","添加成功");
                }else{
                    return R.ok().put("data","添加失败");
                }
            }else{
                return R.ok().put("data","添加失败");
            }
        }catch (Exception e){
            return R.ok().put("data","添加失败");
        }
//        finally {
//            return R.ok().put("data","添加失败");
//        }
    }

    @PostMapping("/searchPackById")
    @Operation(description = "根据id查询设备信息")
    public R searchPackById(@Valid @RequestBody SearchPackByIdForm form){
        HashMap tbPackManger = packMangerService.selectByPrimaryKey(form.getId());
        try {
            JSONArray packList = JSONUtil.parseArray(tbPackManger.get("packList"));
            JSONArray urlList = JSONUtil.parseArray(tbPackManger.get("urlList"));
            JSONArray verList = JSONUtil.parseArray(tbPackManger.get("verList"));
            JSONArray packTime = JSONUtil.parseArray(tbPackManger.get("packTime"));
            if(!packList.isEmpty() &&!urlList.isEmpty()&&!verList.isEmpty()){
                if(packList.size()==urlList.size()&&urlList.size()==verList.size()){
                    List<HashMap<String,String>> list=new ArrayList<HashMap<String,String>>();
                    for (int i = 0; i < packList.size(); i++) {
                        HashMap<String, String> p = new HashMap<>();
                        p.put("name",packList.get(i).toString());
                        p.put("url",urlList.get(i).toString());
                        p.put("ver",verList.get(i).toString());
                        p.put("pTime",packTime.get(i).toString());
                        list.add(p);
                    }
                    tbPackManger.put("packageCount",list.size());
                    tbPackManger.put("pName",packList.get(packList.size()-1).toString());
                    tbPackManger.put("pVersion",verList.get(verList.size()-1).toString());
                    tbPackManger.put("packs",list);
                    return R.ok().put("data",tbPackManger);
                }
            }
        }catch (Exception e){
            return R.ok().put("data",tbPackManger);
        }
        finally {
            return R.ok().put("data",tbPackManger);
        }
    }
    @PostMapping("/searchPackByName")
    @Operation(description = "根据设备型号查询设备信息")
    public R searchPackByName(@Valid @RequestBody SearchPackByNameForm form){
        HashMap tbPackManger = packMangerService.selectByName(form.getDeviceName());
        try {
            JSONArray packList = JSONUtil.parseArray(tbPackManger.get("packList"));
            JSONArray urlList = JSONUtil.parseArray(tbPackManger.get("urlList"));
            JSONArray verList = JSONUtil.parseArray(tbPackManger.get("verList"));
            if(!packList.isEmpty() &&!urlList.isEmpty()&&!verList.isEmpty()){
                if(packList.size()==urlList.size()&&urlList.size()==verList.size()){
                    List<HashMap<String,String>> list=new ArrayList<HashMap<String,String>>();
                    for (int i = 0; i < packList.size(); i++) {
                        HashMap<String, String> p = new HashMap<>();
                        p.put("name",packList.get(i).toString());
                        p.put("url",urlList.get(i).toString());
                        p.put("ver",verList.get(i).toString());
                        list.add(p);
                    }
                    tbPackManger.put("packageCount",list.size());
                    tbPackManger.put("pName",packList.get(packList.size()-1).toString());
                    tbPackManger.put("pVersion",verList.get(verList.size()-1).toString());
                    tbPackManger.put("packs",list);
                    tbPackManger.put("appVersion","1.0.1");
                    return R.ok().put("data",tbPackManger);
                }
            }
        }catch (Exception e){
            if(tbPackManger==null){
                tbPackManger=new HashMap<>();
            }
            tbPackManger.put("appVersion","1.0.1");
            return R.ok().put("data",tbPackManger);
        }
        finally {
            if(tbPackManger==null){
                tbPackManger=new HashMap<>();
            }
            tbPackManger.put("appVersion","1.0.1");
            return R.ok().put("data",tbPackManger);
        }
    }
}
